/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import entity.Construct;
import entity.Cost;
import exception.ValueNotFoundException;
import java.util.Collection;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import session.manager.CheckBeanLocal;
import session.manager.ConstructManagerBeanLocal;
import session.manager.PlayerManagerBeanLocal;
import session.manager.ResourceManagerBeanLocal;
import session.timed.ConstructTimedBeanLocal;

/**
 *
 * @author antonio
 */
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Stateless
public class ConstructBuilderBean implements ConstructBuilderBeanLocal {
    
    @EJB
    CheckBeanLocal checkBean;
    
    @EJB
    ConstructTimedBeanLocal timedBean;
    
    @EJB
    ResourceManagerBeanLocal resourceManager;
    
    @EJB
    ConstructManagerBeanLocal constructManager;
    
    @EJB
    PlayerManagerBeanLocal playerManager;
    
    @Override
    public boolean buildConstruct(String username, String constructName, int amount) {
        Construct construct = constructManager.findConstruct(constructName);
        if(construct == null) {
            throw new ValueNotFoundException("Il costrutto specificato non è presente nel database");
        }
        if (checkBean.checkEra(username, constructName )
                && checkBean.checkSlot(username, amount)
                && checkBean.chekCost(username, constructName, amount)) {
            Collection<Cost> cost = construct.getCostCollection();
            for (Cost c : cost) {
                resourceManager.decrese(username, c.getResource1().getName(), c.getAmount() * amount);
            }
            constructManager.beginConstructs(username, constructName, amount);
            timedBean.initTimer(username, constructName, amount);
            return true;
        }
        return false;
    }
    
    @Override
    public boolean destroyConstruct(String username, String constructName, int amount) {
        Construct construct = constructManager.findConstruct(constructName);
        if(construct == null) {
            throw new ValueNotFoundException("Il costrutto specificato non è presente nel database");
        }
        if (checkBean.checkConstruct(username, constructName, amount)) {
            Collection<Cost> cost = construct.getCostCollection();
            for (Cost c : cost) {
                int a = (int) (c.getAmount() * amount * 0.5);
                resourceManager.increse(username, c.getResource1().getName(), a);
            }
            constructManager.destroyConstructs(username, constructName, amount);
            return true;
        }
        return false;
    }

}
